package com.light.component;

import com.light.enums.Level;
import com.light.util.NoticeUtils;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.layout.HBox;
import javafx.stage.DirectoryChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.Window;
import org.apache.commons.lang3.StringUtils;

import java.io.File;

public class AddLocalProjectPane extends Stage {

    private static final String INIT_DIR = "D:";
    private final Window window;
    private final TextField textField = new TextField();
    private final Button load = new Button("加载");
    private final HBox inputHBox = new HBox(10);

    private final DirectoryChooser dirChooser = new DirectoryChooser();

    private static AddLocalProjectPane instance;

    public AddLocalProjectPane(Window window) {
        super();
        this.window = window;

        initialize();
        Scene scene = new Scene(inputHBox, 700, 100);
        //设置此窗口在优先级最高 屏蔽其他窗口
        setScene(scene);
        initModality(Modality.WINDOW_MODAL);
        getIcons().add(new Image("/icons/git.png"));
        setTitle("添加本地项目");
        initOwner(window);
        initEvent();
    }

    public static void showPane(Window window) {
        if (instance == null) {
            instance = new AddLocalProjectPane(window);
        }
        instance.show();
    }

    private void initialize() {
        //输入框横向布局
        inputHBox.setAlignment(Pos.CENTER);
        //错误提示横向布局
        HBox noticeHBox = new HBox(10);
        noticeHBox.setAlignment(Pos.CENTER);

        //输入框
        textField.setPromptText("请输入代码存放路径");
        textField.setMinWidth(550);
        //设置打开窗口时焦点不在输入框中
        textField.setFocusTraversable(false);
        //加载按钮
        inputHBox.getChildren().addAll(textField, load);
    }

    private void initEvent() {
        load.setOnAction(loadBtn -> {
            System.out.println("用户输入路径：" + textField.getText());
            //错误提示
            try {
                if (StringUtils.isEmpty(textField.getText())) {
                    NoticeUtils.show(window, "请输入路径", Level.WARN);
                } else {
                    File file = new File(textField.getText());
                    if (file.exists()) {
                        //todo 输入正确，读取文件夹中内容

                    } else {
                        NoticeUtils.show(getScene().getWindow(), "该路径不存在或路径下无内容", Level.DANGER);
                    }
                }
            } catch (Exception e) {
                NoticeUtils.show(getScene().getWindow(), "路径不正确", Level.DANGER);
            }
        });

        textField.setOnMouseClicked(event -> {
            dirChooser.setInitialDirectory(new File(INIT_DIR));
            dirChooser.showDialog(window);
        });
    }
}
